<template>
  <el-row >
   <el-col span="10">
     <basic-container style="height: 100%;overflow-y: auto">
       <el-tag>商品基本信息</el-tag>
       <el-divider></el-divider>

       <div class="step">
       <avue-form  ref="spuForm" v-model="form" :option="formOption" @submit="nullWork">
         <template slot-scope="scope" slot="spuPostage">
             <el-switch v-model="spuPostage" @change="handlePostage"></el-switch>
             <el-input v-show="spuPostage" style="width:80px;margin-left: 40px" v-model="form.spuPostage" placeholder="0.00"></el-input>
         </template>
         <template slot-scope="scope" slot="spuDescribe">
           <avue-ueditor v-model="form.spuDescribe"
                         :options="ueditorOptions"></avue-ueditor>
         </template>

       </avue-form>
       </div>
     </basic-container>
   </el-col>
    <el-col span="10">
      <basic-container>
        <el-tag type="success" @click="ttt">属性信息</el-tag>

        <el-divider></el-divider>
        <div class="step">
        <avue-empty v-show="attrData.length<1" desc="请先选择分类"></avue-empty>
        <el-form   ref="attrForm" v-show="attrData.length>0"  style="margin-bottom: 50px;">
          <el-form-item v-for="o in attrData" :key="o.id" >
            <el-row >
              <el-col  :span="5">
                <div >
                  <el-checkbox v-model="o.isAttr">
                    <el-tag :type="o.isAttr===true?o.isSale===true?o.id===mainAttr?'danger':'warning':'success':'info'">
                      {{o.attrName}}
                    </el-tag>
                  </el-checkbox>
                </div>
              </el-col>
              <el-col :span="4">
                <div >
                  <el-checkbox :disabled="!o.isAttr"   v-model="o.isSale">销售属性</el-checkbox>
                </div>
              </el-col>
              <el-col :span="4">
                <div >
                  <el-radio v-show="o.isSale" v-model="mainAttr" :label="o.id">主属性</el-radio>
                </div>
              </el-col>
              <el-col :span="10">
                <el-select
                  :disabled="!o.isAttr"
                  v-model="o.attrValue"
                  multiple
                  filterable
                  allow-create
                  default-first-option
                  placeholder="输入完毕后回车继续输入">
                  <el-optio>
                  </el-optio>
                </el-select>
              </el-col>
            </el-row>
          </el-form-item>
          <el-divider></el-divider>
          <el-button type="primary" @click="handleSku">下一步</el-button>
        </el-form >

        </div>
      </basic-container>
      <el-dialog title="主属性规格图片配置"
                 :visible.sync="skuImageBox"
                 width="60%">

        <avue-crud ref="skuImageCrud" :option="skuImageOption" :data="skuImageData" >
          <template slot="menuLeft">
            <el-tag type="danger">图片请上传jpg/png格式.认真核实所有信息避免对您造成损失</el-tag>
          </template>
        </avue-crud>
        <el-row>
          <el-col :push="22" :span="2" style="margin-top: 20px">
            <el-button type="primary"  @click="handleSkuBox">下一步</el-button>
          </el-col>

        </el-row>


      </el-dialog>
      <el-dialog title="商品规格配置"
                 :visible.sync="skuBox"
                 width="60%">

        <avue-crud ref="skuCrud" :option="skuOption" :data="form.skuData" >
          <template slot="menuLeft">

            <el-tag type="danger">图片请上传jpg/png格式.认真核实所有信息避免对您造成损失</el-tag>
          </template>
          <template slot="menu" slot-scope="{row,index,size,type}">
            <el-button @click="deleteSkuRow(index)" :size="size" :type="type">删除</el-button>
          </template>
        </avue-crud>
        <el-row>
          <el-col :push="22" :span="2" style="margin-top: 20px">
            <el-button type="primary"  @click="submitForm">提交</el-button>
          </el-col>

        </el-row>


      </el-dialog>

    </el-col>
    <el-col span="4">
      <basic-container>
        <el-tag type="warning">具体流程</el-tag>

        <el-divider></el-divider>
        <div class="step">
          <el-steps direction="vertical" :active="1">
            <el-step title="填写基本信息" description="您需要根据商品的品类填写对应信息,请确保这些信息符合实际商品,否则将影响审核"></el-step>
            <el-step title="确定销售规格" description="销售属性将自动组合为您的商品规格,确认您的规格及其他信息"></el-step>
            <el-step title="向仓库发送货物" description="当然,如果您希望自己发货,您可以使用自己的本地仓库.不过,我们还是向您推荐官方仓库."></el-step>
            <el-step title="等待审核" description="当您审核后并且该商品所有规格库存不为0时可以进行上架"></el-step>
            <el-step title="开始销售" description="您的商品开始销售"></el-step>
          </el-steps>
        </div>
      </basic-container>

    </el-col>
  </el-row>

</template>

<script>
  import { getAttrByCategory} from "@/api/category/category";
  import { add} from "@/api/product/spu";
  import avueUeditor from 'avue-plugin-ueditor'
  export default {
    component:{
      avueUeditor
    },
      data(){
          return {
            //富文本配置
            ueditorOptions:{
              action: '/api/ocm-resource/oss/endpoint/put-file',
              customConfig: {},//wangEditor编辑的配置
              props: {
                res: "data",
                url: "link"
              },
            },
            //
            skuImageData:[],
            skuImageBox:false,
            skuImageOption:{
              addBtn:false,
              addRowBtn:false,
              menu:false,
              saveBtn:false,
              editBtn:false,
              delBtn:false,
              cellBtn:false,
              border: true,
              index: true,
              column: [{
                label:'属性名',
                prop: 'attrName',
                cell: false,
              },{
                label:'属性值',
                prop: 'attrValue',
                cell: false,
              },{
                label:'主图',
                prop: 'attrImage',
                type: "upload",
                listType: 'picture-img',
                propsHttp: {
                  res: 'data',
                  url: 'link',
                },
                action: '/api/ocm-resource/oss/endpoint/put-file',
                rules: [{
                  required: true,
                  message: "请输入主图（图片数组第一张）",
                  trigger: "blur"
                }],
                cell: true
              }]
            },
            spuPostage:true,
            form:{
              skuData:[],
              saleAttrId:[],
              selectCategory:0,
              attr:[],
              spuDescribe:'',

            },
            mainAttr:0,
            attrData:[],
            skuOption:{
              addBtn:false,
              addRowBtn:false,
              saveBtn:false,
              editBtn:false,
              cellBtn:false,
              menuWidth:100,
              border: true,
              index: true,
              column: [{
                label:'标题',
                prop: 'skuTitle',
                cell: true,
                rules: [
                  {
                    required: true,
                    message: '请输入标题',
                    trigger: 'blur'
                  }
                ]
              },{
                label:'价格',
                prop: 'skuPrice',
                cell: true,
                type:'number',
                rules: [{
                  required: true,
                  message: "请输入价格",
                  trigger: "blur"
                }],
              },{
                label:'主图',
                prop: 'skuImage',
                type: "upload",
                listType: 'picture-img',
                propsHttp: {
                  res: 'data',
                  url: 'link',
                },
                action: '/api/ocm-resource/oss/endpoint/put-file',
                rules: [{
                  required: true,
                  message: "请输入主图（图片数组第一张）",
                  trigger: "blur"
                }],
                cell: false
              }, {
                  label:'规格',
                  prop: 'saleAttr',
                  type: 'array',
                  rules: [
                    {
                      required: true,
                      message: '请输入',
                      trigger: 'blur'
                    }
                  ],
                  cell: false
              }]
            },
            skuBox:false,
            formOption:{
              column: [
                {
                  type: 'input',
                  label: '标题',
                  span: 15,
                  display: true,
                  prop: 'spuTitle',
                  rules: [{
                    required: true,
                    message: "标题",
                    trigger: "blur"
                  }]
                },
                {
                  type: 'input',
                  label: '副标题',
                  span: 15,
                  display: true,
                  prop: 'spuInfo',
                  rules: [{
                    required: true,
                    message: "请输入副标题",
                    trigger: "blur"
                  }]
                },
                {
                  type: 'input',
                  label: '发货地',
                  span: 15,
                  display: true,
                  prop: 'spuPlace',
                  rules: [{
                    required: true,
                    message: "请输入副标题",
                    trigger: "blur"
                  }]
                },
                {
                  label: "视频",
                  prop: "spuVideo",
                  accept:"video/mp4",
                  type: "upload",
                  listType: 'picture-img',
                  propsHttp: {
                    res: 'data',
                    url: 'link',
                  },
                  action: '/api/ocm-resource/oss/endpoint/put-file',
                  tip: '只能上传mp4视频，且不超过10M',
                  hide:true,
                  span:24,
                  rules: [{
                    required: false,
                    message: "请输入视频",
                    trigger: "blur"
                  }]
                },
                {
                  label: "主图",
                  prop: "spuThumb",
                  type: "upload",
                  span: 24,
                  listType: 'picture-img',
                  propsHttp: {
                    res: 'data',
                    url: 'link',
                  },
                  action: '/api/ocm-resource/oss/endpoint/put-file',
                  tip: '只能上传jpg/png图片，且不超过500kb',
                  rules: [{
                    required: true,
                    message: "请输入主图（图片数组第一张）",
                    trigger: "blur"
                  }]
                },
                {
                  label: "图片",
                  hide:true,
                  dataType: 'string',
                  type: "upload",
                  row:true,
                  span:24,
                  listType: 'picture-card',
                  propsHttp: {
                    res: 'data',
                    url: 'link',
                  },
                  action: '/api/ocm-resource/oss/endpoint/put-file',
                  tip: '只能上传jpg/png图片，且不超过500kb',
                  prop: "spuImages",
                  rules: [{
                    required: true,
                    message: "请输入图片",
                    trigger: "blur"
                  }]
                },
                {
                  label: "图片详情",
                  hide:true,
                  prop: "spuDescribe",
                  dataType: 'string',
                  type: "upload",
                  row:true,
                  span:23,
                  listType: 'picture-card',
                  propsHttp: {
                    res: 'data',
                    url: 'link',
                  },
                  canvasOption: {    excelBtn:true,
                    text: 'ocm',
                  },
                  action: '/api/ocm-resource/oss/endpoint/put-file',
                  tip: '只能上传jpg/png图片，且不超过500kb',
                  rules: [{
                    required: true,
                    message: "请输入图片详情",
                    trigger: "blur"
                  }]
                },
                {
                  label: "所属分类",
                  prop: "selectCategory",
                  type: "cascader",
                  dicUrl: "/api/ocm-product/category/list",
                  props: {
                    label: "categoryName",
                    value: "id",
                  },
                  rules: [{
                    required: true,
                    message: "请输入所属分类",
                    trigger: "click"
                  }]
                },
                {
                  label: '邮费',
                  span: 24,
                  display: true,
                  prop: 'spuPostage'
                },
              ],
              labelPosition: 'left',
              labelSuffix: '：',
              labelWidth: 120,
              gutter: 0,
              menuBtn: false,
              submitBtn: true,
              submitText: '提交',
              emptyBtn: true,
              emptyText: '清空',
              menuPosition: 'center'
            },

            l_attrData:[],
          }
      },
      watch:{
          'form.selectCategory'(data){
            if(data[1]!==undefined){
              getAttrByCategory(1,500,{'r.categoryId_equal':data[1]}).then(res=>{
                this.attrData=res.data.data.records
                this.form.spuCategory=data[1]
              })

            }
          }
      },
      created() {

      },
      methods:{
        submitForm(){
         this.$refs['skuCrud'].validateCellForm().then(res=>{
            if(JSON.stringify(res)==='{}'){
              add(this.form).then(()=>{
                this.$message({
                  type: "success",
                  message: "添加成功!"
                });
                this.skuBox=false
                this.skuImageBox=false
                this.$refs['spuForm'].resetForm()
                this.attrData.splice(0,this.attrData.length)
              })
            }
          });

        },
        handleSkuBox(){
          let index=0;
          let skuOpt = this.cartesianProduct(this.l_attrData);
          console.log(skuOpt)
          let nowAttr=skuOpt[0][0];
          skuOpt.forEach((attr)=>{
            console.log(attr)
            if(!(nowAttr===attr[0])){
              index+=1;
              nowAttr=attr[0]
            }
            this.form.skuData.push({
              skuTitle:attr.join(','),
              saleAttr:attr,
              skuPrice:0.00,
              skuImage:this.skuImageData[index].attrImage,
              $cellEdit:true
            })
          })
          this.skuBox=true
        },
        handlePostage(){
          this.form.spuPostage=0.00
        },
        nullWork(form,done){
          done()
        },
        deleteSkuRow(index){
          if(this.form.skuData.length<2){
            this.$message({
              type: "error",
              message: "至少存在一个销售规格!"
            });
            return;
          }
          this.form.skuData.splice(index,1);
        },
        handleSku(){
          this.$refs['spuForm'].validate((valid) => {
            if (valid) {
              //取消表单锁定
              this.$refs['spuForm'].allDisabled=false
              //初始化数据
              this.form.skuData=[]
              this.form.attr=[]
              this.form.saleAttrId=[]
              let attrData=[]
              let mainAttr=false
              for(let i=0;i<this.attrData.length;i++){
                if(this.attrData[i].isAttr){
                  if(this.attrData[i].attrValue&&this.attrData[i].attrValue.length<1){
                    this.$message({
                      type: "error",
                      message: "属性值不能为空!"
                    });
                    return;
                  }
                  //判断是否是销售属性 取出主属性
                  console.log(this.attrData[i])

                  if(this.attrData[i].isSale){
                    if(this.attrData[i].id===this.mainAttr){
                      attrData.unshift(this.attrData[i])
                      mainAttr=this.attrData[i]
                      this.form.saleAttrId.unshift(this.attrData[i].id)
                      continue
                    }else{
                      attrData.push(this.attrData[i])
                      this.form.saleAttrId.push(this.attrData[i].id)
                      continue
                    }
                  }
                  //格式化数组数据 转为string 即普通属性不需要分条储存
                  let a = JSON.parse(JSON.stringify(this.attrData[i]))
                  a.attrValue= a.attrValue.toString()
                  //将id转为attrId->用于后端要求格式
                  a.attrId=a.id
                  a.id=""
                  this.form.attr.push(a)
                }
              }
              if(!mainAttr){
                this.$message({
                  type: "error",
                  message: "请确定主属性"
                });
                return;
              }
              if(this.form.attr.length<1||attrData.length<1){
                this.$message({
                  type: "error",
                  message: "请填写基本属性"
                });
                return;
              }
              //配置主属性图片数据
              this.skuImageData=[]
              mainAttr.attrValue.forEach(t=>{
                this.skuImageData.push({
                  attrId:mainAttr.id,
                  attrName:mainAttr.attrName,
                  attrValue:t,
                  attrImage:'',
                  $cellEdit:true
                })
              })

              const o = [];
              for(let i = 0 ; i<attrData.length;i++){
                o.push(attrData[i].attrValue)
              }
              console.log(this.form)
              this.l_attrData=o

              this.skuImageBox=true
            } else {
              this.$message({
                type: "error",
                message: "您有必填项没有填噢!"
              });
            }
          });

        },
        //构造笛卡尔乘积函数
        cartesianProduct(arr){
          return arr.reduce(function(a,b){
            return a.map(function(x){
              return b.map(function(y){
                return x.concat(y);
              })
            }).reduce(function(a,b){ return a.concat(b) },[])
          }, [[]])
        },
      }
    }
</script>

<style scoped>
  .step{
    height:calc(100vh - 230px);
    overflow-y: auto;

  }
</style>
